package com.example.system.service.impl;


import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.R;
import com.example.system.entity.ChatRecord;
import com.example.system.entity.Patient;
import com.example.system.mapper.ChatRecordMapper;
import com.example.system.mapper.PatientMapper;
import com.example.system.service.IChatRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王鹤蒲
 * @since 2024-02-28
 */
@Service
public class ChatRecordServiceImpl extends ServiceImpl<ChatRecordMapper, ChatRecord> implements IChatRecordService {

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Override
    public ChatRecord add(ChatRecord chatRecord) {
        chatRecordMapper.insert(chatRecord);
        return chatRecord;
    }

    @Override
    public R findByUserName(String sender, String receiver) {
        List<ChatRecord> chatRecordList=chatRecordMapper.findByUserName(sender,receiver);
        chatRecordList.forEach(chatRecord -> {
            if(chatRecord.getReceiver().equals(sender)&&chatRecord.getSender().equals(receiver)){
                chatRecord.setReaded(1);
                chatRecordMapper.updateById(chatRecord);
            }
        });
        return R.success(chatRecordList);
    }

    @Override
    public R findUnreadNums(String receiver) {
        List<ChatRecord> chatRecordList=chatRecordMapper.findByReceiver(receiver);
        Map<String,List<ChatRecord>> collect=chatRecordList.stream().collect(Collectors.groupingBy(ChatRecord::getSender));
        Dict dict=new Dict();
        collect.forEach((sender,senderChatRecordList)-> dict.set(sender,senderChatRecordList.size()));
        return R.success(dict);
    }

    @Override
    public R selectOnlineInquiryPatientList(String sender) {
        List<Patient> patientList=patientMapper.queryOnlineInquiryPatientNameList(sender);
        return R.success(patientList);
    }
}
